//Copyright (c) 2010, Goodwine & Tibia ML
//Licensed under new BSD License.

// Adds '[Permalink]' to news.
chrome.extension.sendRequest({action : 'loadJQuery'}, jQueryLoad);
function jQueryLoad(data) {
	if (data != null) {
		eval(data);
		var dates = [];
		// Parses the news, and it gets the max and minimum date to check for in the archive.
		$('.NewsHeadlineDate').each(function() {
			dates.push(new Date(this.innerText.replace(/\s/ig, '.')));
		});
		if(dates.length) {
			var max = dates[0];
			var min = dates[0];
			for(var i in dates) {
				if(dates[i].getTime() > max.getTime())
					max = dates[i];
				if(dates[i].getTime() < min.getTime())
					min = dates[i];
			}
				getNewsLinks(min.getDate(), min.getMonth()+1, min.getFullYear(), max.getDate(), max.getMonth()+1, max.getFullYear());
		}
	} else {
		console.warn('News Linker: Failed to load jQuery');
	}
}

// XHR form with date limits to read and set the news id as a link.
function getNewsLinks(bday, bmonth, byear, eday, emonth, eyear)
{
	var request = new XMLHttpRequest();
	request.onreadystatechange = function() {
		if (request.readyState != 4) return;
		$('.NewsHeadlineBackground .NewsHeadlineText').each(function() {
			var x = new RegExp('<a.*?href=.*?subtopic=newsarchive.*?id=(.*?)&.*?>' + this.innerText.substr(0,70).replace('.','\\.') + '.*?<\\/a>','i');
			var id = request.responseText.match(x)[1];
			var link = document.createElement('a');
			link.innerText = '[Permalink]';
			link.href = 'http://www.tibia.com/news/?subtopic=newsarchive&id='+id;
			link.style.position = 'absolute';
			link.style.right = '10px';
			link.style.top = '8px';
			link.style.color = 'white';
			link.style.fontSize = '7pt';
			this.parentElement.appendChild(link);
		});
	};
	var params =
	'filter_begin_day=' + bday +
	'&filter_begin_month=' + bmonth +
	'&filter_begin_year=' + byear +
	'&filter_end_day=' + eday +
	'&filter_end_month=' + emonth +
	'&filter_end_year=' + eyear +
	'&filter_ticker=ticker'+
	'&filter_article=article'+
	'&filter_news=news'+
	'&filter_cipsoft=cipsoft'+
	'&filter_community=community'+
	'&filter_development=development'+
	'&filter_support=support'+
	'&filter_technical=technical';
	var url = 'http://www.tibia.com/news/?subtopic=newsarchive';
	request.open('POST', url);
	request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	request.send(params);
	return false;
}